package other.xsy.paas;

import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEvent;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventRequest;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventResponse;
import com.rkhd.platform.sdk.data.model.Contract;
import com.rkhd.platform.sdk.data.model.Order;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import other.xsy.paas.utils.HCXObjectService;

import java.util.List;

/**
 * @Description: 合同编号变更重置订单编号
 * @Author: lys
 * @Date: 2025-07-29 16:05
 */
public class OrderCodeReset implements RuleEvent {

    private static Logger logger = LoggerFactory.getLogger();

    private static HCXObjectService hcxObjectService = new HCXObjectService();

    /**
     * 触发规则触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public RuleEventResponse execute(RuleEventRequest request) throws ScriptBusinessException {
        startReset(request.getDataId());

        RuleEventResponse response = new RuleEventResponse();
        response.setSuccess(true);
        response.setMsg("");
        return response;
    }

    public static void main(String[] args) {
        OrderCodeReset orderCodeReset = new OrderCodeReset();
        orderCodeReset.startReset(3914295210052933L);
    }


    public void startReset(Long contractId) {
        try {
            // 获取合同编码
            logger.info("重置合同下的订单编码 = " + contractId);
            Contract contract = new Contract();
            contract.setId(contractId);
            contract = hcxObjectService.get(contract);
            String contractCode = contract.getContractCode();

            // 获取订单集合
            String sql = String.format("select id,po from _order where contractId = %s order by createdAt", contractId);
            List<Order> orderList = (List<Order>) hcxObjectService.query(sql);
            if (orderList == null || orderList.size() == 0) {
                logger.info("合同下的订单集合为空");
                return;
            }

            // 修改订单编号
            for (int i = 0; i < orderList.size(); i++) {
                Order order = orderList.get(i);
                order.setPo(contractCode + "-" +  String.format("%02d", i + 1));
            }
            logger.info("orderList = " + orderList);
            hcxObjectService.batchUpdate(orderList);
            logger.info("重置合同下的订单编码完成");

        } catch (Exception e) {
            logger.error("重置订单编码异常:" + e.getMessage());
        }
    }


}
